package edu.ccut.saturn.basevalidate.prvalidate;

import edu.ccut.saturn.component.DefaultSaturnValidate;
import edu.ccut.saturn.component.ValidateResult;

public class IsIPAdressValidate extends DefaultSaturnValidate {

	private static final String ipRegExpr = "(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)";
	
	private static final String integerRegExpr = "^[1-9]\\d*|0$";    //非负整数

	public void doValidate(Object value, Object[] args, ValidateResult result) {

		if (!(value.toString()).matches(ipRegExpr)) {
			sendError(_ERROR_, value, result);
		} else {
			String ipAdress = value.toString();
			int startIndex = 0;
			int endIndex = ipAdress.indexOf(".");
			for (int i = 0; i < 4; i++) {
				
				String section = ipAdress.substring(startIndex, endIndex);
				
				if (section != null && isValueValidate(section)) {
					startIndex = endIndex + 1;
					if (i < 2) {
						endIndex = ipAdress.indexOf(".", startIndex);
					} else {
						endIndex = ipAdress.length();
					}
				} else {
					sendError(_ERROR_, value, result);
				}
				
			}
		}
	}

	private Boolean isValueValidate(String section) {
		
		if(!(section.toString()).matches(integerRegExpr)) {
			return false;
		}
		
		if (Integer.parseInt(section) >= 256) {
			return false;
		}
		
		return true;
	}
}
